<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>优惠券管理</el-breadcrumb-item>
      <el-breadcrumb-item>优惠券配置</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <div slot="header">
        <span>基本信息</span>
      </div>
      <!-- 表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="110px"
      >
        <el-form-item label="券名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入，将用于客户端券名称展示（建议10字以内）"
          ></el-input>
        </el-form-item>
        <el-form-item label="券分类" prop="classify">
          <el-select
            v-model="addForm.classify"
            placeholder="请选择"
            filterable
            clearable
            @change="selectCla"
          >
            <el-option label="优惠券" value="1"> </el-option>
            <el-option label="运费券" value="2"> </el-option>
            <el-option label="兑换券" value="3"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="券类别" prop="category">
          <el-select
            v-model="addForm.category"
            placeholder="请选择"
            filterable
            clearable
          >
          <el-option
            v-for="item in selectClass"
            :key="item.id"
            :label="item.name + '【' + item.id + '】'"
            :value="item.id"
          >
          </el-option>
            <!-- <el-option label="满减券" value="1"> </el-option>
            <el-option label="折扣券" value="2"> </el-option>
            <el-option label="特惠券" value="3"> </el-option>
            <el-option label="免邮券" value="4"> </el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="券类型" prop="type">
          <el-select
            v-model="addForm.type"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option key="1" label="通用券" value="1"> </el-option>
            <el-option key="2" label="专用券" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用分类" prop="apply_class">
          <el-select
            v-model="addForm.apply_class"
            placeholder="请选择"
            filterable
            clearable
            :multiple="addForm.type == 1"
            v-if="update"
            @change="clearApplyGoodsConfig"
          >
            <el-option
              v-for="item in selectData.product_type"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用范围说明" prop="apply_explain">
          <el-input
            v-model="addForm.apply_explain"
            placeholder="请输入，将用于客户端优惠券可用品类或商品的说明（建议20字内）"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="面值"
          prop="face_value"
          v-show="addForm.category == 1"
          :rules="
            addForm.category == 1
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            placeholder="请输入，将用于客户端券面值展示"
            v-model="addForm.face_value"
            oninput="value=value.replace(/[^\d.]/g,'')"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="折扣"
          prop="discount"
          v-show="addForm.category == 2"
          :rules="
            addForm.category == 2
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            placeholder="请输入，将用于客户端券折扣展示"
            v-model="addForm.discount"
            oninput="value=value.replace(/[^\d.]/g,'')"
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="使用金额"
          prop="amount"
          v-show="addForm.category == 1 || addForm.category == 2"
          :rules="
            addForm.category == 1 || addForm.category == 2
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            placeholder="请输入，将用于客户端券限制的最低使用金额说明"
            v-model="addForm.amount"
            oninput="value=value.replace(/[^\d.]/g,'')"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="特惠价"
          prop="preferential_price"
          v-show="addForm.category == 3"
          :rules="
            addForm.category == 3
              ? [
                  { required: true, message: '请输入', trigger: 'blur' },
                  { validator: decimalValid, trigger: 'blur' }
                ]
              : []
          "
        >
          <el-input
            placeholder="请输入，将用于客户端可用商品的特惠价格展示"
            v-model="addForm.preferential_price"
            oninput="value=value.replace(/[^\d.]/g,'')"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期" required>
          <el-col :span="12">
            <el-form-item
              prop="valid"
              v-show="addForm.valid_unit != 4"
              :rules="
                addForm.valid_unit != 4
                  ? [
                      { required: true, message: '请输入', trigger: 'blur' },
                      { type: 'number', message: '请输入数字' }
                    ]
                  : []
              "
            >
              <el-input
                placeholder="请输入，将用户客户端展示"
                v-model.number="addForm.valid"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              prop="valid_start_time"
              v-show="addForm.valid_unit == 4"
              :rules="
                addForm.valid_unit == 4
                  ? [
                      {
                        required: true,
                        message: '请选择日期',
                        trigger: 'change'
                      }
                    ]
                  : []
              "
            >
              <el-date-picker
                type="date"
                placeholder="请选择"
                v-model="addForm.valid_start_time"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="valid_unit">
              <el-select v-model="addForm.valid_unit" placeholder="请选择">
                <el-option value="1" label="日"></el-option>
                <el-option value="2" label="月"></el-option>
                <el-option value="3" label="年"></el-option>
                <el-option value="4" label="截止日期"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="限制使用区域" prop="area_limit_flag">
          <el-radio
            v-model="addForm.area_limit_flag"
            label="1"
            @change="handleChangeAreaLimit"
            >限制</el-radio
          >
          <el-radio
            v-model="addForm.area_limit_flag"
            label="0"
            @change="handleChangeAreaLimit"
            >不限制</el-radio
          >
        </el-form-item>
        <el-form-item
          label="区域限制方式"
          prop="area_limit_way"
          v-show="addForm.area_limit_flag == 1"
          :rules="
            addForm.area_limit_flag == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="addForm.area_limit_way"
            placeholder="请选择区域限制方式"
            @change="changeRule"
          >
            <el-option value="1" label="按省份"></el-option>
            <el-option value="2" label="按城市"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="使用区域范围"
          prop="range_name"
          v-show="addForm.area_limit_flag == 1"
          :rules="
            addForm.area_limit_flag == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-input placeholder="请选择区域范围" v-model="addForm.range_name">
            <el-link type="primary" slot="append" @click="openRangeDialog"
              >选择区域</el-link
            >
          </el-input>
          <el-input v-model="addForm.area_limit" v-show="false"> </el-input>
        </el-form-item>
        <el-form-item label="使用区域描述" prop="ranged_desc">
          <el-input
            v-model="addForm.ranged_desc"
            placeholder="请输入，将用于客户端券使用的区域限制说明（建议20字内）"
          ></el-input>
        </el-form-item>
        <el-form-item label="使用数量限制">
          <el-col :span="12">
            <el-select
              v-model="addForm.quantity_limit_unit"
              placeholder="请选择限制周期"
            >
              <el-option value="每日" label="每日"></el-option>
              <el-option value="每月" label="每月"></el-option>
              <el-option value="每年" label="每年"></el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="addForm.quantity_limit"
              placeholder="请输入限制数量"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="使用间隔限制">
          <el-col :span="12">
            <el-select
              v-model="addForm.space_limit_unit"
              placeholder="请选择间隔周期"
            >
              <el-option value="日" label="日"></el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="addForm.space_limit"
              placeholder="请输入间隔数量"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="其他使用说明" prop="explain">
          <el-input
            v-model="addForm.explain"
            placeholder="请输入，将用于客户端券使用的其他限制说明（建议10字内）"
          ></el-input>
        </el-form-item>
        <el-form-item label="领取渠道" prop="channel">
          <el-radio-group v-model="addForm.channel">
            <el-radio label="1">小程序优惠券列表</el-radio>
            <el-radio label="2">第三方系统</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="addForm.remark"
            show-word-limit
            maxlength="500"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 10px">
      <div slot="header">
        <span>适用商品配置</span>
      </div>
      <el-form
        :model="applyGoodsForm"
        :rules="applyGoodsFormRules"
        ref="applyGoodsFormRef"
        label-width="110px"
        label-position="left"
      >
        <el-form-item label="适用规则" prop="apply_flag">
          <el-radio-group
            @change="changeApplyFlag"
            v-model="applyGoodsForm.apply_flag"
          >
            <el-radio label="1">限品类</el-radio>
            <el-radio label="2">限商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="适用产品"
          v-show="applyGoodsForm.apply_flag == 1"
          prop="productList"
          :rules="
            applyGoodsForm.apply_flag == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-checkbox-group v-model="applyGoodsForm.productList">
            <el-checkbox
              v-for="item in selectData.product"
              :key="item.id"
              :label="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          label="适用商品"
          v-show="applyGoodsForm.apply_flag == 2"
          prop="goodsList"
          :rules="
            applyGoodsForm.apply_flag == 2
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-checkbox-group v-model="applyGoodsForm.goodsList">
            <el-checkbox
              v-for="item in selectData.goods"
              :key="item.id"
              :label="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </el-card>
    <el-row style="margin-top: 10px">
      <el-button @click="$router.push('/coupon/configureList')">
        取 消
      </el-button>
      <el-button class="theme-background-color" @click="saveInfo"
        >保 存</el-button
      >
    </el-row>
    <!-- 选择省份区域对话框 -->
    <chooseMultipleProvince
      :provinceVisible.sync="provinceVisible"
      :checkedRanges="checkedRanges"
      @showProvincesData="updateRanges"
    ></chooseMultipleProvince>

    <!-- 选择城市区域对话框 -->
    <ChooseMultipleCity
      :cityVisible.sync="cityVisible"
      :checkedRanges="checkedRanges"
      @showCitiesData="updateRanges"
    ></ChooseMultipleCity>
  </div>
</template>

<script>
import chooseMultipleProvince from '../region/ChooseMultipleProvince.vue'
import ChooseMultipleCity from '../region/ChooseMultipleCity.vue'

export default {
  components: { chooseMultipleProvince, ChooseMultipleCity },
  data() {
    var decimalValid = (rule, val, callback) => {
      val = val + ''
      if (val.indexOf('.') !== -1 && val.split('.').length > 2) {
        // 防止输入多个小数点
        callback(new Error('输入正确格式'))
      } else {
        // 不足补位
        val = Number(val).toFixed(2)
        // this.priceRuleForm.price = val
        this.addForm[rule.field] = val
        callback()
      }
    }
    return {
      addForm: {
        name: '',
        classify: '',
        category: '',
        type: '',
        apply_class: '',
        apply_explain: '',
        value: '',
        face_value: '',
        discount: '',
        amount: '',
        preferential_price: '',
        valid: '',
        valid_start_time: '',
        valid_unit: '',
        area_limit_flag: '0',
        area_limit_way: '',
        range_name: '',
        area_limit: '',
        ranged_desc: '全国',
        quantity_limit_unit: '',
        quantity_limit: '',
        space_limit_unit: '',
        space_limit: '',
        explain: '',
        channel: '',
        remark: ''
      },
      selectClass: [],
      addFormRules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        classify: [{ required: true, message: '请选择', trigger: 'change' }],
        category: [{ required: true, message: '请选择', trigger: 'change' }],
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        apply_class: [{ required: true, message: '请选择', trigger: 'change' }],
        apply_explain: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        valid_unit: [{ required: true, message: '请选择', trigger: 'change' }],
        area_limit_flag: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        ranged_desc: [{ required: true, message: '请输入', trigger: 'blur' }],
        channel: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      update: true, // 控制多选变化时不渲染组件，计算完再渲染组件
      selectData: { product_type: [], product: [], goods: [] },
      decimalValid,

      // 省市控件勾选用的数据
      checkedRanges: [],
      provinceVisible: false,
      cityVisible: false,

      applyGoodsForm: {
        apply_flag: '',
        productList: [],
        goodsList: [],
        apply_value: ''
      },
      applyGoodsFormRules: {
        apply_flag: [{ required: true, message: '请选择', trigger: 'change' }],
        productList: [{ required: true, message: '请选择', trigger: 'change' }],
        goodsList: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getSelectData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/Data/find', {
        code: 'product_type',
        level: 2
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData.product_type = res.data.product_type
    },
    handleChangeAreaLimit() {
      if (this.addForm.area_limit_flag === '1') {
        this.addForm.ranged_desc = ''
      } else {
        this.addForm.ranged_desc = '全国'
      }
    },
    updateRanges(data) {
      this.addForm.area_limit = data.code.join(',')
      this.addForm.range_name = data.name.join(',')
      this.addForm.ranged_desc = this.addForm.range_name
    },
    changeRule() {
      this.addForm.area_limit = ''
      this.addForm.range_name = ''
      this.addForm.ranged_desc = ''
    },

    openRangeDialog() {
      if (this.addForm.area_limit_way === '') {
        this.$message({
          message: '请先选择区域限制方式',
          type: 'warning'
        })
      } else {
        if (parseInt(this.addForm.area_limit_way) === 1) {
          this.provinceVisible = true
        } else {
          this.cityVisible = true
        }
        // console.log(this.addForm.range_value)
        this.checkedRanges = this.addForm.area_limit
          ? this.addForm.area_limit.split(',')
          : []
      }
    },
    selectCla(val) {
      if (val == 1) {
        this.selectClass = [
          { name: '满减券', id: '1' },
          { name: '折扣券', id: '2' },
          { name: '特惠券', id: '3' }
        ]
      } else if (val == 2) {
        this.selectClass = [
          { name: '满减券', id: '1' },
          { name: '特惠券', id: '3' },
          { name: '免邮券', id: '4' }
        ]
      } else if (val == 3) {
        this.selectClass = [
          { name: '满减券', id: '1' }
        ]
      } else {
        this.selectClass = []
      }
    },
    changeApplyFlag(val) {
      if (this.addForm.apply_class === '') {
        this.applyGoodsForm.apply_flag = ''
        return this.$message.error('请先选择适用分类')
      }
      // console.log(typeof this.addForm.apply_class)

      const typeCode =
        typeof this.addForm.apply_class === 'object'
          ? this.addForm.apply_class.join(',')
          : this.addForm.apply_class
      if (val == 1) {
        this.getProductData(typeCode)
      } else {
        this.getGoodsData(typeCode)
      }
    },
    async getProductData(typeCode) {
      const { data: res } = await this.$http.post('admin/Data/find', {
        code: 'product',
        type_code: typeCode
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData.product = res.data.product
    },
    async getGoodsData(typeCode) {
      const { data: res } = await this.$http.post('admin/Data/find', {
        code: 'goods',
        type_code: typeCode
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData.goods = res.data.goods
    },
    // 清空适用商品配置的数据
    clearApplyGoodsConfig() {
      this.$refs.applyGoodsFormRef.resetFields()
    },
    async saveInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        this.$refs.applyGoodsFormRef.validate(async (valid2) => {
          if (!valid2) return
          // console.log(this.applyGoodsForm)
          // this.addForm.value = this.valueCompute

          const postData = JSON.parse(
            JSON.stringify(Object.assign(this.addForm, this.applyGoodsForm))
          )
          postData.apply_class =
            typeof postData.apply_class === 'object'
              ? postData.apply_class.join(',')
              : postData.apply_class
          postData.apply_value = this.applyValue
          postData.value = this.valueCompute

          const { data: res } = await this.$http.post(
            'admin/CouponConfig/add',
            postData
          )
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.$router.push('/coupon/configureList')
        })
      })
    }
  },
  computed: {
    valueCompute: {
      get: function () {
        let val = ''
        if (this.addForm.category == 1) {
          val = this.addForm.face_value
        } else if (this.addForm.category == 2) {
          val = this.addForm.discount
        } else if (this.addForm.category == 3) {
          val = this.addForm.preferential_price
        }
        return val
      },
      set: function (val) {
        // console.log(val)
        // console.log(this.addForm)
        if (this.addForm.category == 1) {
          this.addForm.face_value = val
        } else if (this.addForm.category == 2) {
          this.addForm.discount = val
        } else if (this.addForm.category == 3) {
          this.addForm.preferential_price = val
        }
      }
    },
    applyValue: {
      get: function () {
        let val = ''
        if (this.applyGoodsForm.apply_flag == 1) {
          val = this.applyGoodsForm.productList.join(',')
        } else {
          val = this.applyGoodsForm.goodsList.join(',')
        }
        return val
      },
      set: function (val) {
        // console.log(val)
        if (this.applyGoodsForm.apply_flag == 1) {
          this.applyGoodsForm.productList = val.split(',')
        } else {
          this.applyGoodsForm.goodsList = val.split(',')
        }
      }
    }
  },
  watch: {
    'addForm.type'() {
      this.update = false
      setTimeout(() => {
        this.update = true
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 600px;
  margin-left: 15px;
  .el-select {
    width: 100%;
  }
}
</style>
